﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace SharpDepend.Classes
{
    public struct ProfilerInstance
    {
        public string TypeName { get; set; }

        public string Info { get; set; }

        public override string ToString()
        {
            return TypeName + ": " + Info;
        }
    }

    public class ProfilerStatistics
    {

        private static List<WeakReference> mReferences = new List<WeakReference>();
        private static List<ProfilerInstance> output = new List<ProfilerInstance>();
        private static StringBuilder mSB = new StringBuilder();

        private string DEBUGNAME;
        private ICollection pList;

        public ProfilerStatistics(string DEBUGNAME, ICollection pList)
        {
            //string callingAssembly = System.Reflection.Assembly.GetCallingAssembly().FullName;

            this.DEBUGNAME = DEBUGNAME;
            this.pList = pList;

            mReferences.Add(new WeakReference(this));
        }

        /// <summary>
        /// Get informations of all list by SharpDepend. (Slow operation)
        /// </summary>
        /// <returns>List of ProfilerInstance.</returns>
        public static List<ProfilerInstance> GetListsInfo()
        {
            output.Clear();

            for (int i = mReferences.Count - 1; i >= 0; i--)
            {
                var reference = mReferences[i];

                if (reference.IsAlive)
                {
                    ProfilerStatistics obj = (ProfilerStatistics)reference.Target;

                    output.Add(new ProfilerInstance
                    {
                        TypeName = obj.DEBUGNAME,
                        Info = "Count: " + obj.pList.Count
                    });
                }
                else
                {
                    // Remove reference if it is not used anymore.
                    mReferences.RemoveAt(i);
                }
            }

            return output;
        }
        
        public static string GetListsInfoAsText()
        {
            var list = GetListsInfo();

            mSB.Clear();

            foreach (var item in list)
            {
                mSB.AppendLine(item.ToString());

            }

            return mSB.ToString();
        }
    }
}
